//
//  WeatherViewController.m
//  天气预报
//
//  Created by mac on 16/1/21.
//  Copyright © 2016年 YF_S. All rights reserved.
//

#import "WeatherViewController.h"
#import "RealtimeModel.h"
#import "RealtimeView.h"
//#import "LifeView.h"
//#import "FutureWeatherModel.h"
#import "FutureCollectionView.h"
#import <CoreLocation/CoreLocation.h>

@interface WeatherViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>{
    
    CLLocationManager *_manager;//设置全局的管理者
    
    CLGeocoder *_geocoder;//地理编码管理者
    
    RealtimeView *_realtimeView;//实时天气视图
    
    RealtimeModel *_realtimeModel;//Model
    
//    LifeView *_liftView;//生活
    
    //未来几天数组
    NSMutableArray *futureDataArr;
    FutureCollectionView *_collectionView;
    
    BOOL isFirstLoad;
}

@property (weak, nonatomic) IBOutlet UITextField *textFiled;

@end

@implementation WeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"天气预报";
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_home.jpg"]];
    
    //设置textfiled的代理
    _textFiled.delegate = self;
    
    
    //开启定位功能
    [self LoadCoreLocation];
    
    //获取当的位置
    [self reverseCode];
    
//    //数据持久化
//    NSUserDefaults *userDefaults = [[NSUserDefaults alloc]init];
//    
//    //获取bool类型的值
//    isFirstLoad = [userDefaults boolForKey:@"isFirstLoad"];
//    
//    if (isFirstLoad == NO) {
//        
//        //开启定位功能
//        [self LoadCoreLocation];
//        
//        //获取当的位置
//        [self reverseCode];
//        
//        [userDefaults setBool:YES forKey:@"isFirstLoad"];
//        
//    }else{
//    
//        //获取当的位置
//        [self reverseCode];
//    }
}

//定位功能
-(void)LoadCoreLocation{

    //初始化manager对象
    _manager = [[CLLocationManager alloc]init];
    
    //1.判断当前系统是否开启定位系统
    if (![CLLocationManager locationServicesEnabled]) {
        
        NSLog(@"系统定位服务未开启");
        
        return;
    }
    
    //2.判断当前应用是否获取定位授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        
        //设置代理
        _manager.delegate = self;
        
        //首次启动授权状态为kCLAuthorizationStatusNotDetermined
        
        //更改授权状态 应用程序使用时给予定位授权
        [_manager requestWhenInUseAuthorization];
        
        //允许应用程序一直使用定位
//        [_manager requestAlwaysAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
    
        NSLog(@"禁止修改授权状态");
    }
    
    //3.修改授权需要 更改应用程序的info.plist文件
    //NSLocationWhenInUseUsageDescription ---- kCLAuthorizationStatusAuthorizedWhenInUse
    //NSLocationAlwaysUsageDescription ---- kCLAuthorizationStatusAuthorizedAlways
    
    //4.设置管理者属性
    //设置定位精度
    /*
     extern const CLLocationAccuracy kCLLocationAccuracyBestForNavigation //导航时最精确位置__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);
     extern const CLLocationAccuracy kCLLocationAccuracyBest; //最精确位置
     extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters; //精确到十米范围
     extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;
     extern const CLLocationAccuracy kCLLocationAccuracyKilometer;
     extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;
     */
    _manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    //开启定位
    [_manager startUpdatingLocation];
    
    //初始化_geocoder
    _geocoder = [[CLGeocoder alloc]init];
}

-(void)reverseCode{

    //初始化CLLocation对象
//    CLLocation *loc = [[CLLocation alloc] initWithLatitude:35 longitude:117];
    
    //取出经纬度
    CLLocationCoordinate2D coordinate = _manager.location.coordinate;
    
    NSLog(@"coordinate is %f,%f",coordinate.longitude,coordinate.latitude);
    
    //反编码
    [_geocoder reverseGeocodeLocation:_manager.location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (error) {
            NSLog(@"输入的地址在火星");
            return;
        }
        else
        {
            //获取到反编码对象
            CLPlacemark *pm = [placemarks firstObject];
            /*
             pm.country  国家
             pm.locality 城市
             pm.subLocality 子城市
             pm.thoroughfare 街道
             pm.subThoroughfare 子街道
             */
            
//            NSString *address = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",pm.country,pm.locality,pm.subLocality,pm.thoroughfare,pm.subThoroughfare];
            
//            NSLog(@"addrss is:%@",address);
//            
//            NSLog(@"pm.locality :%@",pm.locality);
            
//            NSLog(@"pm.subLocality is %@",pm.subLocality);
            
            //获取数据
            [self loadDatas:pm.locality];
        }
    }];
}

//当用户定位信息发生改变时调用
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    
    
        //数据持久化
        NSUserDefaults *userDefaults = [[NSUserDefaults alloc]init];
    
        //获取bool类型的值
        isFirstLoad = [userDefaults boolForKey:@"isFirstLoad"];
    
        if (isFirstLoad == NO) {
    
            //开启定位功能
            [self LoadCoreLocation];
    
            //获取当的位置
            [self reverseCode];
    
            [userDefaults setBool:YES forKey:@"isFirstLoad"];
    
        }else{
        
            //获取当的位置
//            [self reverseCode];
        }

    
//    NSLog(@"count is:%ld",locations.count);
//    
//    //1.从数组中获取到CLLocation对象 （数组中可能会存在多个对象，取出第一个最精确的对象）
//    CLLocation *location = locations[0];
    
    //取出经纬度
//    CLLocationCoordinate2D coordinate = location.coordinate;
    
//    NSLog(@"精度：%f,纬度：%f",coordinate.longitude,coordinate.latitude);
    
}


//点击return键时调用
-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    NSString *changeStr = textField.text;
    
    if (![changeStr isEqualToString:@""]) {
        
        [self loadDatas:changeStr];
    }else{
    
        //地里编码
        [self reverseCode];
    }
    
    //失去第一响应者
    [textField resignFirstResponder];
    
    return YES;
}

//获取数据
-(void)loadDatas:(NSString *)cityName{

    //数据地址
    NSString *url = @"http://op.juhe.cn/onebox/weather/query";
    
    //拼接参数
    NSDictionary *parameters = @{@"key":kAppKey,@"cityname":cityName};
        
    //获取数据
    [NetWorking getHomeTimeLineWithURLString:url withParameters:parameters success:^(id result) {
        
        //
        NSDictionary *result1 = [result objectForKey:@"result"];
        
        NSDictionary *data = [result1 objectForKey:@"data"];
        
        //实时天气
        NSDictionary *realtime = [data objectForKey:@"realtime"];
        
        //初始化实时天气Model
        _realtimeModel = [[RealtimeModel alloc]initWithDic:realtime];
        
        //加载实时天气
        [self loadRealtimeView];
        
//        //life
//        NSDictionary *life = [data objectForKey:@"life"];
//        
//        NSDictionary *info = [life objectForKey:@"info"];
//        
//        //加载视图
////        [self createLiftView];
//        
//        _liftView.info = info;
        
//        //未来几天
//        NSArray *weather = [data objectForKey:@"weather"];
//        
//        for (NSDictionary *dic in weather) {
//            
//            FutureWeatherModel * model = [[FutureWeatherModel alloc]initWithDic:dic];
//            
//            [futureDataArr addObject:model];
//        }
        
        [self createCollectionView];
        
        _collectionView.result = result;
    }];
}

//未来天气
-(void)createCollectionView{

    if (!_collectionView) {
        
        _collectionView = [[FutureCollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-_textFiled.height-4*2-_realtimeView.height-64)];
        
        _collectionView.top = _realtimeView.bottom;
        
        [self.view addSubview:_collectionView];
    }
    
    
    _collectionView.dataArr = futureDataArr;
}

////加载lift的天气
//-(void)createLiftView{
//
//    if (!_liftView) {
//        
//        _liftView = [[[NSBundle mainBundle] loadNibNamed:@"LifeView" owner:nil options:nil] objectAtIndex:0];
//        
//        _liftView.top = _realtimeView.bottom;
//        
//        _liftView.backgroundColor = [UIColor clearColor];
//        
//        [_bgView addSubview:_liftView];
//    }
//}

//加载实时天气
-(void)loadRealtimeView{

    
    if (!_realtimeView) {
        
        _realtimeView = [[[NSBundle mainBundle]loadNibNamed:@"RealtimeView" owner:nil options:nil] objectAtIndex:0];
        
        _realtimeView.backgroundColor = [UIColor clearColor];
        
        _realtimeView.top = _textFiled.bottom + 4;
        
        [self.view addSubview:_realtimeView];
    }
    
    _realtimeView.model = _realtimeModel;
}

//结束编辑
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
